package xls;

import guiParts.ErrorGui;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ReadXLS {
	
	
	private boolean emailsWrong = false;
	
	private static ReadXLS instance = null;
	
	private ReadXLS() {
	}
	
	public static ReadXLS getInstance(){
		if(instance == null) {
			instance = new ReadXLS();
		}
		return instance;
	}

	public Set<String> readXLS(String xlsFile) {
		Set<String> emails = new HashSet<String>();
		try {
			POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(xlsFile));
			System.out.println("Read " + xlsFile);
			HSSFWorkbook wb = new HSSFWorkbook(fs);
			HSSFSheet sheet = wb.getSheetAt(0);
			Cell cell;
			for (Row row2 : sheet) {
				if ((cell = row2.getCell(0)) != null) {

					String email;
					if ((email = cell.getStringCellValue()) != null && email.length() > 1) {
						try {
						InternetAddress emailAdd = new InternetAddress(email);
							emailAdd.validate();
							System.out.println("Add this email-address :" + email);
							emails.add(email);
						} catch (AddressException e) {
							emailsWrong = true;
							e.printStackTrace();
						}
					}
				}
			}

		}
		catch (IOException io) {
			System.err.print("Error while reading xls-file");
			@SuppressWarnings("unused")
			ErrorGui errorGui = new ErrorGui("Fehler beim Lesen der XLS-Datei");
			io.printStackTrace();
		} 
		System.out.println("Found " + emails.size() + " email-adress(es).");
		return emails;
	}

	public boolean isEmailsWrong() {
		return emailsWrong;
	}

	public void setEmailsWrong(boolean emailsWrong) {
		this.emailsWrong = emailsWrong;
	}
}
